/**
 * 板块管理路由
 */

var router = require('express').Router();
var assertAlljs = require('../bin/util/assert-alljs');
var userTool = require('../bin/user');
var blockTool = require('../bin/block');

router.get('/block(.*)?', async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(user, {role:'admin'});
    if (await assert(checkMessage))
        return;

    res.locals.blocksDic = blockTool.getBlocksDic(res.locals.blocks, true);
    res.render('dyn.block.html', { blocksDic:JSON.stringify(res.locals.blocksDic) });
});

router.post('/saveblock', async function(req, res){
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(user, {role:'admin'});
    if (await assert(checkMessage))
        return;

    if (await assert(req.body.blocks == null || req.body.blocks === '', '板块配置为空'))
        return;

    let blocks = null;
    try{
        blocks = JSON.parse(req.body.blocks);
    } catch (err){
        await assert(err);
        return;
    }

    let result = await blockTool.setBlocks(blocks);
    if (await assert(result instanceof Error))
        return;

    await assert(true, '已保存板块配置');
});

module.exports = router;